﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BDH.UTL
{
    using System.Management;
    using System.Security.Cryptography;

    public static class Sys
    {
        public static string GetCpuId()
        {
            string cpuInfo = string.Empty;
            ManagementClass mc = new ManagementClass("win32_processor");
            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                if (cpuInfo == "")
                {
                    // Lấy về mã số Processor.
                    cpuInfo = mo.Properties["processorID"].Value.ToString();
                    break;
                }
            }
            return cpuInfo;
        }

        public static string HddId(string drive = "C")
        {
            ManagementObject dsk = new ManagementObject(@"win32_logicaldisk.deviceid=""" + drive + @":""");
            dsk.Get();
            string volumeSerial = dsk["VolumeSerialNumber"].ToString();
            return volumeSerial;
        }

        public static string EncodeMD5(string inputString)
        {
            MD5 md5 = MD5.Create();
            byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(inputString));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
                sb.Append(data[i].ToString("x2"));

            return sb.ToString();
        }

        public static string StringKey(string str)
        {
            string result = "";
            str = str.Trim();
            for (int i = 0; i < str.Length; i++)
            {
                if (i < 25)
                {
                    if (i != 0 && i % 5 == 0)
                        result += "-";
                    result += str[i];
                }
            }
            return result;
        }

        public static string CreateKey()
        {
            string str1 = Sys.EncodeMD5(Sys.GetCpuId());
            string str2 = Sys.EncodeMD5(Sys.HddId());
            str1 += str2;
            string result = Text.ToAllUpper(Sys.StringKey(Sys.EncodeMD5(str1)));
            return result;
        }

        public static string CreateLicense()
        {
            string str = EncodeMD5(CreateKey());
            str += Sys.GetCpuId();
            str += "ABCDEFGHIJKLMNOPQSRTXYZW";
            str += "WZYXTRSQPONMLKJIHGFEDCBA";
            string s = Text.ToAllUpper(StringKey(EncodeMD5(str)));
            return s;
        }

        public static bool Check(string str1, string str2)
        {
            if (str1 == str2)
                return true;
            return false;
        }

    }
}
